import React, { useState, useEffect } from 'react';
import { obj_float, obj_str, KFind, cline, uDb, loc, KSelect, ck_empty, useKForm, KDlg } from 'sui';
import { fix_state } from './cmd';

const DlgState = (props) => {
    const form = useKForm(props.data);

    const ck = {
        state: (v) => ck_empty(v, loc("l_131")),
    };

    const getLst = () => {
        if (!props.lst) {
            return fix_state();
        }

        return props.lst;
    };

    return (
        <KDlg {...props} title={loc("l_131")} ck={ck} form={form}>
            <KSelect label={loc("l_131")} name="state" form={form} lst={getLst()}/>
        </KDlg>
    );
};

const DlgBsn = (props) => {
    const [stock, setStock] = useState();
    const form = useKForm();

    useEffect(() => {
        if (!props.open) {
            return;
        }

        const tsn = obj_str(props.data, "tech");
        const dw = obj_str(props.data, "dw");
        const cmd = { line: cline(), k: tsn };

        setStock(null);

        uDb(null, "tech/get", cmd, tr => {
            const mt = obj_str(tr, "mt");
            const mod = mt === "G" ? "stell" : "cera";
            const ball = obj_str(tr, "ball");

            uDb(null, `${mod}/list`, cmd, cr => {
                const ret = [];

                cr.forEach(d => {
                    if (ball !== obj_str(d, "ball")) {
                        return;
                    }

                    const std = obj_float(d, "std");
                    const sub = obj_float(d, "sub");
                    let dw_c = "";

                    if (mod === "cera") {
                        dw_c = `${std + sub}`;
                    } else {
                        dw_c = `${sub}`;
                    }

                    if (dw !== dw_c) {
                        return;
                    }

                    d["name"] = dw_c;
                    d["mt"] = mt;

                    ret.push(d)
                });

                setStock(ret);
            });
        });
    }, [props.open, props.data]);

    const hdone = (v) => {
        const bsn = obj_str(v, "bsn");
        const f = stock.find(d => d.sn === bsn);
        if (!f) {
            return null;
        }

        const cmd = {
            bsn: bsn,
            std: obj_float(f, "std"),
            sub: obj_float(f, "sub"),
            dw: obj_float(f, "name"),
            ball: obj_float(f, "ball"),
            mt: obj_str(f, "mt"),
        };

        props.hcmd(cmd);
    };

    const ck = {
        bsn: (v) => ck_empty(v, loc("l_131")),
    };

    const ext = [
        {key: "std", name: loc("l_715"), width: 100},
        {key: "sub", name: loc("l_801"), width: 100},
    ];

    return (
        <KDlg {...props} title={loc("l_131")} ck={ck} form={form} hcmd={hdone}>
            <KFind label={loc("l_488")} name="bsn" form={form} list={stock} c2={loc("l_802")} ext={ext}/>
        </KDlg>
    );
};

export {DlgBsn, DlgState};
